package com.example.demo.client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.Cookie;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;


public class HttpHttpsUtil {

    public static final String UTF_8 = "UTF-8";
    
    public static String httpUrlGet(String url, Map<String, String> queryParas) {
        return httpUrlGet(buildUrlWithQueryString(url, queryParas));
    }

    public static String httpUrlGet(String GetUrl, Cookie[] cookies,String coookieUrl) {
        try {
            URL url = new URL(GetUrl); // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.setRequestProperty("Content-Type", "application/x-javascript;charset=utf-8");
            String cookieStr="";
            for(Cookie co:cookies){
                String cookeStrin=co.getName()+"="+co.getValue()+"; Domain="+coookieUrl+"; Path="+co.getPath();
                connection.addRequestProperty("Cookie", cookeStrin);
                cookieStr+=cookeStrin;
            }
            connection.setRequestMethod("GET");
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF_8));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            /*System.out.println(sb.toString());*/
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }
    }

    public static String httpUrlGet(String GetUrl) {
        try {
            URL url = new URL(GetUrl); // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.setRequestProperty("Content-Type", "application/x-javascript;charset=utf-8");

            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF_8));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            /*System.out.println(sb.toString());*/
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return e.toString();
        }
    }

    public static String httpUrlDataPost(String PostUrl, String objDate) {
        System.out.println(PostUrl);
        String result = null;
        try {
            URL url = new URL(PostUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            connection.connect();
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
            dataout.write(objDate.getBytes(UTF_8));
            dataout.flush();
            dataout.close();
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF_8));
            String line;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = bf.readLine()) != null) {
                stringBuffer.append(line).append(System.getProperty("line.separator"));
            }
            bf.close();
            connection.disconnect();
            /*System.out.println(stringBuffer.toString());*/
            result = stringBuffer.toString();
        } catch (MalformedURLException e) {
            result = e.getMessage();
            e.printStackTrace();
        } catch (IOException e) {
            result = e.getMessage();
            e.printStackTrace();
        }
        return result;
    }

    public static String httpUrlPost(String PostUrl) {
        String result = null;
        try {
            URL url = new URL(PostUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/x-javascript;charset=utf-8");
            connection.connect();
            DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
            dataout.flush();
            dataout.close();
            BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF_8));
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line).append(System.getProperty("line.separator"));
            }
            bf.close();
            connection.disconnect();
            /*System.out.println(stringBuilder.toString());*/
            result = stringBuilder.toString();
        } catch (MalformedURLException e) {
            result = e.getMessage();
            e.printStackTrace();
        } catch (IOException e) {
            result = e.getMessage();
            e.printStackTrace();
        }
        return result;
    }

    private static final String GET = "GET";
    private static final String POST = "POST";
    private static String CHARSET = "UTF-8";

    /**
     * Build queryString of the url
     */
    private static String buildUrlWithQueryString(String url, Map<String, String> queryParas) {
        if (queryParas == null || queryParas.isEmpty()) {
            return url;
        }

        StringBuilder sb = new StringBuilder(url);
        boolean isFirst;
        if (url.indexOf('?') == -1) {
            isFirst = true;
            sb.append('?');
        } else {
            isFirst = false;
        }

        for (Entry<String, String> entry : queryParas.entrySet()) {
            if (isFirst) {
                isFirst = false;
            } else {
                sb.append('&');
            }

            String key = entry.getKey();
            String value = entry.getValue();
            if (StringUtils.isNotBlank(value)) {
                try {
                    value = URLEncoder.encode(value, CHARSET);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
            sb.append(key).append('=').append(value);
        }
        return sb.toString();
    }

}
